package demo523;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;


    import java.sql.*;
import java.util.Scanner;

    public class LoginDemo {

        // 数据库连接信息
        private static final String URL = "jdbc:mysql://localhost:3306/usersDb";
        private static final String DB_USERNAME = "root";
        private static final String DB_PASSWORD = "123456";

        /**
         * 登录功能
         */
        public static void main(String[] args) throws ClassNotFoundException, SQLException {
            // 1. 注册（加载）驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取数据库连接
            Connection connection = DriverManager.getConnection(URL, DB_USERNAME, DB_PASSWORD);

            // 3. 编写SQL语句
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            // 4. 执行SQL语句
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 5. 给问号赋值
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String username = scanner.next();
            System.out.println("请输入密码：");
            String password = scanner.next();

            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);

            // 6. 查询是否有结果的ResultSet，接收查询语句查询出来的结果
            ResultSet resultSet = preparedStatement.executeQuery();

            // 7. 处理结果
            if (resultSet.next()) {
                System.out.println("登录成功！");
            } else {
                System.out.println("登录失败！");
            }

            // 8. 关闭资源
            resultSet.close();
            preparedStatement.close();
            connection.close();
        }
    }


